// 收货地址编辑页面
import { 
  getAddressById, 
  createAddress, 
  updateAddress,
  showSuccess,
  showError,
  showLoading,
  hideLoading
} from '../../../utils/addressApi.js';

Page({
  data: {
    mode: 'create', // create: 新建, edit: 编辑
    addressId: null,
    
    // 表单数据
    formData: {
      recipientName: '',
      phoneNumber: '',
      province: '',
      city: '',
      county: '',
      detailedAddress: '',
      addressTag: '家',
      isDefault: false
    },
    
    // 地址标签选项
    tagOptions: ['家', '公司', '学校', '其他'],
    
    // 页面状态
    loading: false,
    submitting: false,
    
    // 地区选择
    regionArray: [[], [], []], // 省市区数组
    regionIndex: [0, 0, 0], // 选中的省市区索引
    customRegion: false // 是否显示自定义地区选择
  },

  onLoad(options) {
    const { mode, id } = options;
    
    this.setData({
      mode: mode || 'create',
      addressId: id ? parseInt(id) : null
    });

    // 如果是编辑模式，加载地址详情
    if (mode === 'edit' && id) {
      this.loadAddressDetail(id);
    }

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: mode === 'edit' ? '编辑地址' : '新建地址'
    });
  },

  /**
   * 加载地址详情
   */
  async loadAddressDetail(id) {
    try {
      showLoading('加载中...');
      const result = await getAddressById(id);
      
      if (result.success && result.data) {
        this.setData({
          formData: {
            recipientName: result.data.recipientName || '',
            phoneNumber: result.data.phoneNumber || '',
            province: result.data.province || '',
            city: result.data.city || '',
            county: result.data.county || '',
            detailedAddress: result.data.detailedAddress || '',
            addressTag: result.data.addressTag || '家',
            isDefault: result.data.isDefault || false
          }
        });
      } else {
        showError(result.message || '加载地址信息失败');
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载地址详情失败:', error);
      showError('网络错误，请重试');
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } finally {
      hideLoading();
    }
  },

  /**
   * 输入框变化处理
   */
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  /**
   * 地区选择
   */
  onRegionChange(e) {
    const { value } = e.detail;
    
    this.setData({
      [`formData.province`]: value[0],
      [`formData.city`]: value[1],
      [`formData.county`]: value[2]
    });
  },

  /**
   * 地址标签选择
   */
  onTagSelect(e) {
    const { tag } = e.currentTarget.dataset;
    
    this.setData({
      'formData.addressTag': tag
    });
  },

  /**
   * 默认地址开关
   */
  onDefaultChange(e) {
    const { value } = e.detail;
    
    this.setData({
      'formData.isDefault': value
    });
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { formData } = this.data;
    
    if (!formData.recipientName.trim()) {
      showError('请输入收货人姓名');
      return false;
    }
    
    if (!formData.phoneNumber.trim()) {
      showError('请输入手机号');
      return false;
    }
    
    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.phoneNumber)) {
      showError('请输入正确的手机号');
      return false;
    }
    
    if (!formData.province || !formData.city || !formData.county) {
      showError('请选择省市区');
      return false;
    }
    
    if (!formData.detailedAddress.trim()) {
      showError('请输入详细地址');
      return false;
    }
    
    return true;
  },

  /**
   * 保存地址
   */
  async onSave() {
    if (!this.validateForm()) {
      return;
    }
    
    if (this.data.submitting) {
      return;
    }
    
    try {
      this.setData({ submitting: true });
      showLoading('保存中...');
      
      const { mode, addressId, formData } = this.data;
      let result;
      
      if (mode === 'create') {
        result = await createAddress(formData);
      } else {
        result = await updateAddress(addressId, formData);
      }
      
      if (result.success) {
        showSuccess(mode === 'create' ? '地址创建成功' : '地址更新成功');
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        showError(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存地址失败:', error);
      showError('网络错误，请重试');
    } finally {
      this.setData({ submitting: false });
      hideLoading();
    }
  },

  /**
   * 获取微信地址
   */
  onGetWechatAddress() {
    wx.chooseAddress({
      success: (res) => {
        this.setData({
          'formData.recipientName': res.userName,
          'formData.phoneNumber': res.telNumber,
          'formData.province': res.provinceName,
          'formData.city': res.cityName,
          'formData.county': res.countyName,
          'formData.detailedAddress': res.detailInfo
        });
        showSuccess('微信地址导入成功');
      },
      fail: (error) => {
        console.log('获取微信地址失败:', error);
        if (error.errMsg.includes('deny')) {
          showError('已取消获取微信地址');
        } else {
          showError('获取微信地址失败');
        }
      }
    });
  }
});
